<?php

namespace App\Models\Admin\StatsTask;

use App\Models\Admin\Model;

class StatsTask extends Model
{

    /**
     * 进行类型转换的字段
     *
     * @var array
     */
    protected $casts = [
        'created' => 'timestamp',
        'updated' => 'timestamp'
    ];

    /**
     * 不可批量赋值的字段
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * 初始化
     *
     * @var integer
     */
    const STATUS_INIT = 1;

    /**
     * 推送到队列
     *
     * @var integer
     */
    const STATUS_JOB = 2;

    /**
     * 开始处理
     *
     * @var integer
     */
    const STATUS_START = 3;

    /**
     * 任务成功
     *
     * @var integer
     */
    const STATUS_SUCCEE = 4;

    /**
     * 任务失败
     *
     * @var integer
     */
    const STATUS_ERROR = 5;

    /**
     * 验证任务是否已添加
     *
     * @param int $timed
     * @return boolean
     */
    protected function verifyTaskExist($timed)
    {
        return $this->newQuery()
            ->where('timed', $timed)
            ->exists();
    }

    /**
     * 创建多条任务
     *
     * @param int $timed
     * @param array $datas
     * @param int $status
     * @return \Illuminate\Database\Eloquent\Collection
     */
    protected function initTasks($timed, array $datas = [], $status = self::STATUS_INIT)
    {
        return collect($datas)->map(function ($data) use ($timed, $status) {
            $model = $this->newInstance($data);

            $model->timed = $timed;
            $model->status = $status;

            $model->save();

            return $model;
        });
    }

    /**
     * 获取任务数量
     *
     * @var integer
     */
    const TASK_TAKE = 200;

    /**
     * 获取任务实例【多条】
     *
     * @param int $take
     * @return \Illuminate\Database\Eloquent\Collection
     */
    protected function getTasks($take = self::TASK_TAKE)
    {
        return $this->newQuery()
            ->where('status', self::STATUS_INIT)
            ->take($take)
            ->get();
    }
}
